package com.ugold.common.util.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

/**
 * do 和 bo 的互相转化类
 */
public class BeanSwitchUtils {

	/**
	 * 从DO类型的对象转换为BO类型对象
	 * 
	 * @author dingjian
	 * @date 2019/04/23 09:20:41
	 * @param source
	 * @param targetClz
	 * @return
	 */
	public static <DO, BO> BO do2bo(DO source, Class<BO> targetClz) {
		if (null == source || targetClz == null) {
			return null;
		}
		BO target;
		try {
			target = targetClz.newInstance();
			BeanUtils.copyProperties(target, source);
			// PropertyUtils.copyProperties(target, source);
		} catch (Exception e) {
			throw new IllegalArgumentException("对象copy失败，请检查相关module", e);
		}
		return target;
	}

	/**
	 * 根据BO类型将List<DO>转换成List<BO>对象
	 * 
	 * @author dingjian
	 * @date 2019/04/23 09:23:16
	 * @param sourceList
	 * @param targetClz
	 * @return
	 */
	public static <DO, BO> List<BO> do2bo4List(List<DO> sourceList, Class<BO> targetClz) {
		if (sourceList == null || targetClz == null) {
			return null;
		}
		List<BO> targetList = new ArrayList<>(sourceList.size());
		for (DO obj : sourceList) {
			targetList.add(do2bo(obj, targetClz));
		}
		return targetList;
	}

	/**
	 * Map对象转换
	 * 
	 * @author dingjian
	 * @date 2019/04/23 09:25:34
	 * @param sourceMap
	 * @param targetClz
	 * @return
	 */
	public static <BO, DO, K> Map<K, BO> do2bo4Map(Map<K, DO> sourceMap, Class<BO> targetClz) {
		if (sourceMap == null || targetClz == null) {
			return null;
		}
		Map<K, BO> targetMap = new HashMap<>();
		for (Map.Entry<K, DO> item : sourceMap.entrySet()) {
			K key = item.getKey();
			DO val = item.getValue();
			targetMap.put(key, do2bo(val, targetClz));
		}
		return targetMap;
	}
}
